package com.easylinkin.linkappapi.meterbilling.service;

import com.easylinkin.bases.redis.util.RedisUtil;
import com.easylinkin.linkappapi.meterbilling.util.RechargeConstant;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import site.morn.util.MessageDigestUtils;

import javax.annotation.Resource;
import java.util.Collections;

import static site.morn.constant.DigestConstant.Algorithms.SPRING_B_CRYPT;

/**
 * class info :
 *
 * @author liuqihang
 * @date 2021/8/1 11:07
 */
@Service
public class MeterCodeLoginService implements UserDetailsService {

    @Resource
    RedisUtil redisUtil;

    @Override
    public UserDetails loadUserByUsername(String phone) throws UsernameNotFoundException {
        Object o = redisUtil.get(RechargeConstant.METER_WECHAT_PUBLIC_ACCOUNT_LOGIN_VERIFICATION_CODE_PREFIX + phone);
        if(StringUtils.isEmpty(o)){
            throw new BadCredentialsException("验证码或过期,请重新获取");
        }
        String verificationCode = (String) o;
        verificationCode = MessageDigestUtils.encrypt(SPRING_B_CRYPT, verificationCode);
        return new User(phone,
                verificationCode, true, true, true, true, Collections.emptyList());
    }
}
